<template>
  <div class="submitOrder_Container">
    <!--导航栏-->
    <van-nav-bar @click-left="$router.go(-1)" left-arrow title="提交订单"/>

    <div class="submitOrder_content">
      <!--没有默认地址-->
      <router-link tag="div" class="addAddress" v-if="hasDefault===0" :to="addressPath">
        <van-button type="primary" class="btn_item" round @click="">选择/添加收货地址</van-button>
      </router-link>

      <router-link class="address_Detail" tag="div" :to="addressPath" v-if="hasDefault>0">
        <van-row>
          <van-col span="3" class="locationContainer">
            <van-icon name="location" class="icon_location"/>
          </van-col>
          <van-col span="19" class="addressInfo_Container">
            <p class="address_name">收货人：{{ addressInfo.name }}</p>
            <p class="address_info">收货地址：{{ addressInfo.addressDetail }}</p>
            <p class="address_phone">手机：+86{{ addressInfo.phone }}</p>
          </van-col>
          <van-col span="2" class="arrowContainer">
            <van-icon name="arrow" class="icon_arrow"/>
          </van-col>
        </van-row>
      </router-link>

      <van-panel title="商品信息">
        <van-card :key="item.id" :num="item.count" :origin-price="formatPrice(item.price)"
                  :price="formatPrice(item.salePrice)" :thumb="item.imageUrl" :title="item.name"
                  v-for="item in setGoodsList">
          <div class="desc" slot="desc">
            {{ item.description.length > 32 ? item.description.slice(0, 32) + "..." : item.description }}
          </div>
        </van-card>
      </van-panel>

      <van-cell-group>
        <van-cell label="" :value="dealMoney ? '￥' + (dealMoney.toFixed(2)): '免运费'" title="运费"/>

        <van-field label="留言" placeholder="点击给买家留言" v-model="remark"/>

        <van-cell :value="'￥'+totalCartPrice" style="color:#f44" title="合计"/>

      </van-cell-group>

      <div class="order-footer">购物愉快~</div>
    </div>

    <van-submit-bar :price="totalPrice * 100" button-text="付款" @submit="onSubmit"/>

  </div>
</template>

<script>
import jwi_decode from "jwt-decode";

export default {
  name: "submissionOrders",

  data() {
    return {
      remark: "",
      setGoodsList: [],
      defaultAddress: "",
      type: this.$route.query.type,
      count: this.$route.query.count,
    };
  },

  created() {
    this.getInitData();
  },

  computed: {
    // 是否有默认地址
    hasDefault() {
      return Object.keys(this.defaultAddress).length;
    },
    // 地址信息
    addressInfo() {
      return {
        name: this.defaultAddress.name,
        phone: this.defaultAddress.tel,
        addressDetail: this.defaultAddress.province + " " + this.defaultAddress.city + " "
            + this.defaultAddress.county + " " + this.defaultAddress.addressDetail
      };
    },
    //改变地址的时候进行选择
    addressPath() {
      return "/address/list";
    },

    // 邮费处理
    dealMoney() {
      return this.totalCartPrice >= 150 ? 0 : 6;
    },

    //商品总价格除邮费外总费用
    totalCartPrice() {
      return this.setGoodsList.reduce((total, item) => {
        return total + item.salePrice * item.count;
      }, 0);
    },

    // 商品费用+邮费
    totalPrice() {
      return this.totalCartPrice + this.dealMoney;
    },

    userId() {
      return this.$store.getters.user.userId;
    }

  },

  mounted() {
    let height = document.documentElement.clientHeight || document.body.clientHeight;
    let html = document.getElementsByClassName("submitOrder_Container")[0];
    html.style.height = height + "px";
  },

  methods: {
    //初始化数据
    getInitData() {
      if (localStorage.getItem("selectAddress")) {
        this.getChangeAddress();
        this.getGoodsInfo();
      } else {
        this.getDefaultAddress();
        this.getGoodsInfo();
      }
    },

    // 获取默认地址
    async getDefaultAddress() {
      let userId = jwi_decode(localStorage.getItem("eleToken")).userId;
      let res = await this.$axios.post(this.$api.getDefaultAddress, {userId: userId});
      if (res.status === 200 && res.data.code === 200) {
        this.defaultAddress = res.data.data;
      } else {
        this.$toast(res.data.message);
      }
    },
    //获取地址
    async getChangeAddress() {
      let addressID = localStorage.getItem("selectAddress");
      let res = await this.$axios.post(this.$api.getAddressById, {addressID: addressID});
      if (res.status === 200 && res.data.code === 200) {
        this.defaultAddress = res.data.data;
      } else {
        this.$toast(res.data.message);
      }
    },
    // 获取商品信息
    async getGoodsInfo() {
      //第一次if判断表示的是当前进入的路由是哪个路由 type和count（直接购买还是购物车选中后购买）
      if (parseInt(this.type) === 2) {
        //购物车生成订单
        let setGoodsList = localStorage.getItem("selectedGoodsList");
        let setGoodsIndex = JSON.parse(setGoodsList);
        //数据请求
        let res = await this.$axios.post(this.$api.getCartById, {goodsId: setGoodsIndex});
        if (res.status === 200 && res.data.code === 200) {
          this.setGoodsList = res.data.data;
        } else {
          this.$toast(res.data.message);
        }

      } else {
        //直接购买;
        let bookId = JSON.parse(localStorage.getItem("selectedGoodsList"));
        //发送请求
        let res = await this.$axios.post(this.$api.getBookInfoById, {bookId: bookId[0]});
        //使用存储临时数据
        if (res.status === 200 && res.data.code === 200) {
          this.setGoodsList.push(res.data.data);
          // 设置数量
          this.setGoodsList[0].count = this.count;
        }
      }
    },

    // 提交订单
    async onSubmit() {
      // 判断是否有收货地址
      if (JSON.stringify(this.defaultAddress) === "[]" || !this.defaultAddress.id) {
        this.$toast.fail("请选择收货地址");
        return;
      }

      //创建订单需要的参数
      let params = {
        deliveryAddressId: this.defaultAddress.id, //创建订单需要地址的id
        remark: this.remark,
        shopId: JSON.parse(localStorage.getItem("selectedGoodsList")),
        count: this.$route.query.count,//购买的数量
        freight: this.dealMoney,
        userName: this.defaultAddress.name,
        userId: this.userId
      };
      //条件判断后数据提交创建订单
      let res = await this.$axios.post(this.$api.createdOrder, params);
      if (res.status === 200 && res.data.code === 200) {
        this.$notify({message: "订单创建成功", duration: 1000, background: "#1989fa"});
        setTimeout(() => {
          this.$router.push({path: "/safe/payment", query: {orderId: res.data.data}});
        }, 200);
      } else {
        this.$notify({message: "订单创建失败", duration: 1000, background: "#FE4332"});
      }
    },

    formatPrice(price) {
      return price.toFixed(2);
    }
  },
};
</script>

<style lang="less" scoped>

.submitOrder_Container {
  background-color: #fafafa;

  .submitOrder_content {
    padding-bottom: 80px;
    background-color: #fafafa;

    .addAddress {
      background-color: #fff;
      height: 5rem;
      line-height: 5rem;
      text-align: center;

      .btn_item {
        background-color: #fff;
        border-color: blue;
        color: #000000;
        letter-spacing: 2px;
        font-size: .8rem;
        width: 80%;
      }
    }

    .address_Detail {
      height: 5rem;
      background-color: #fff;

      .locationContainer {
        height: 5rem;
        text-align: center;

        .icon_location {
          margin-top: 1.75rem;
          font-size: 1.5rem;
        }
      }

      .addressInfo_Container {
        height: 5rem;
        font-size: .8rem;

        .address_name {
          margin: 0;
        }

        .address_info {
          letter-spacing: 1px;
          margin: .2rem 0;
        }

        .address_phone {
          margin: 0;
        }

      }

      .arrowContainer {
        height: 5rem;
        text-align: center;

        .icon_arrow {
          margin-top: 1.75rem;
          font-size: 1.5rem;
        }
      }

      &::after {
        content: '';
        display: block;
        height: 2px;
        background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #3283fa 0, #3283fa 45%, transparent 0, transparent 50%);
        background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #3283fa 0, #3283fa 45%, transparent 0, transparent 50%);
        background-size: 80px;
      }

    }

    .van-panel {
      margin: 10px 0;
      padding-bottom: 10px;
    }
  }

  .order-footer {
    text-align: center;
    font-size: 13px;
    padding-top: 10px;
    color: #969799;
  }
}


</style>
